package io;

import java.io.File;

public class FileRectify {

	public static void main(String[] args) throws Exception{
		
		addPrefixToAllFiles(new File("src/exam/ch3/Box"), "package exam.ch3.Box");
		//addPrefixToAllFiles(new File("src/exam/ch16"), "package exam.ch16");
		//addPrefixToAllFiles(new File("src/exam"), "package exam");

	}
	
	public static void addPrefixToAllFiles(File dir, String prefix) throws Exception{
		if(!dir.isDirectory())
		{
			return;
		}
		
		File[] allFilesOfThisDir = dir.listFiles();
		
		for(File file: allFilesOfThisDir)
		{
			//System.out.println(file.getAbsolutePath());
			
			if(file.isDirectory())
			{
				addPrefixToAllFiles(file, prefix+"."+file.getName());
			}
			else
			{
				/*File[] javaSrcFiles = file.listFiles(
						new java.io.FilenameFilter() {
							public boolean accept(File dir, String name) {
								return name.endsWith(".java");
							}
						}
				);*/
				if(!file.getName().substring(file.getName().lastIndexOf('.')).equalsIgnoreCase(".java"))
				{
					continue;
				}
				
				String packageName = prefix + ';' + '\n';
				System.out.println(file.getAbsolutePath());
				
				File srcTemp = fileTempCopy(file);
			
				java.io.ByteArrayInputStream sr = new java.io.ByteArrayInputStream(packageName.getBytes());
				java.io.FileInputStream fis = new java.io.FileInputStream(srcTemp);
				//java.io.StringBufferInputStream sbi = new java.io.StringBufferInputStream();
				java.io.SequenceInputStream sis = new java.io.SequenceInputStream(sr, fis);
				//java.io.BufferedInputStream bis = new java.io.BufferedInputStream(sis);
			
			
				java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
			
				byte[] buff = new byte[8192];
			
				int bytesRead;
				while((bytesRead = sis.read(buff))!=-1)
				{
					fos.write(buff, 0, bytesRead);
				};
			
				fos.close();
				sis.close();
				fis.close();
				sr.close();
				srcTemp.delete();
			}
		}
	}
	
	private static File fileTempCopy(File originalFile) throws Exception{
		String absolutePath = originalFile.getAbsolutePath();
		File tempFile = new File(absolutePath + ".tmp");
		java.io.FileInputStream fis = new java.io.FileInputStream(originalFile);
		java.io.FileOutputStream fos = new java.io.FileOutputStream(tempFile);
		
		byte[] buff = new byte[8192];
		
		int bytesRead;
		while((bytesRead = fis.read(buff))!=-1)
		{
			fos.write(buff, 0, bytesRead);
		};
		fos.close();
		fis.close();
		return tempFile;
	}
}
